package cn.fraudmetrix.octopus.modules.jacoco.controller;

import cn.fraudmetrix.octopus.common.utils.R;
import cn.fraudmetrix.octopus.modules.jacoco.dao.JacocoCoverageDao;
import cn.fraudmetrix.octopus.modules.jacoco.dao.JacocoDao;
import cn.fraudmetrix.octopus.modules.jacoco.entity.JacocoCoverageEntity;
import cn.fraudmetrix.octopus.modules.jacoco.entity.JacocoEntity;
import cn.fraudmetrix.octopus.modules.jacoco.service.ReportGenerator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author libao.zheng
 * @email libao.zheng@tongdun.cn
 * @date 2018/11/29 14:33
 */
@RestController
@RequestMapping("/jacoco")
public class JacocoController {
    @Resource
    private JacocoDao jacocoDao;
    @Resource
    private JacocoCoverageDao jacocoCoverageDao;

    @PostMapping("/report")
    public R getReport(@RequestBody JacocoEntity jacocoEntity) {
        Map<String, Object> map = new HashMap<>();
        List<JacocoEntity> result = jacocoDao.query(jacocoEntity);
        if (result.isEmpty()) {
            map.put("code", 2000);
            map.put("msg", "query app error,请检查app是否存在");
            return R.ok(map);
        }
        JacocoEntity entity = result.get(0);
        entity.setIncremental(jacocoEntity.isIncremental());
        return new ReportGenerator().getJacocoReport(entity, jacocoCoverageDao);
    }

    @PostMapping("/queryAll")
    public List<JacocoEntity> queryAll() {
        return jacocoDao.queryAll();
    }

    @PostMapping("/query")
    public List<JacocoEntity> query(@RequestBody JacocoEntity jacocoEntity) {
        return jacocoDao.query(jacocoEntity);
    }

    @PostMapping("/add")
    public boolean add(@RequestBody JacocoEntity jacocoEntity) {
        jacocoDao.add(jacocoEntity);
        JacocoCoverageEntity jacocoCoverageEntity = new JacocoCoverageEntity(
                jacocoEntity.getAppId(), jacocoEntity.getAppName(), "incremental"
        );
        jacocoCoverageDao.add(jacocoCoverageEntity);
        jacocoCoverageEntity.setCoverageType("full");
        return jacocoCoverageDao.add(jacocoCoverageEntity);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody JacocoEntity jacocoEntity) {
        JacocoCoverageEntity jacocoCoverageEntity = new JacocoCoverageEntity(
                jacocoEntity.getAppId(), jacocoEntity.getAppName(), "");
        jacocoCoverageDao.updateAppName(jacocoCoverageEntity);
        return jacocoDao.update(jacocoEntity);
    }

}
